﻿
Partial Class Email
    Inherits System.Web.UI.Page

    Dim strAppPath As String = System.AppDomain.CurrentDomain.BaseDirectory()

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            Dim strID As String = ""
            strID = Request.QueryString("id")
            If strID = "" Then objMultiView.ActiveViewIndex = 0 : litMessageViewError.Text = "Invalid request because id is blank" : Exit Sub
            If Page.IsPostBack = False Then objMultiView.ActiveViewIndex = 1
            If objMultiView.ActiveViewIndex = 1 Then
                txtUsername.Focus()
                'IF ANY PROCESSING NEEDS TO OCCUR BEFORE RENDERING THE LOGIN PAGE PUT IT HERE
            End If
        Catch
            Response.Write("Error in Page_Load: " & Err.Description)
        End Try
    End Sub

    Protected Sub butValidate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles butValidate.Click
        Try
            Dim bolPassedFirstAuthenticationTest As Boolean = True
            If txtUsername.Text = "" Then bolPassedFirstAuthenticationTest = False
            If txtPassword.Text = "" Then bolPassedFirstAuthenticationTest = False
            If txtUsername.Text.Contains("@") = False Then bolPassedFirstAuthenticationTest = False
            If txtUsername.Text.Contains(".") = False Then bolPassedFirstAuthenticationTest = False
            If bolPassedFirstAuthenticationTest = False Then litMessageViewUsernamePassword.Text = "<font style=""color:red"">Invalid username or password because of a blank or because of an invalid email address format</font>" : Exit Sub
            Dim strID As String = ""
            strID = Request.QueryString("id")
            Session("LOGGEDIN" & strID) = "NO"
            Dim strDirectoryName As String = strAppPath & "Data\" & strID
            If System.IO.Directory.Exists(strDirectoryName) = False Then litMessageViewAttachmentsAndSecureText.Text = "<font style=""color:red"">Invalid request because directory doesn't exist</font>" : Exit Sub
            objMultiView.ActiveViewIndex = 2 'SET THE VIEW TO DISPLAY THE ATTACHMENT DATA
            Dim bolPassedSecondAuthenticationTest As Boolean = False
            Dim strSenderFromParm As String = ""
            strSenderFromParm = ReadParm(strAppPath & "Data\" & strID & "\meta\parm.dat", "SENDER")
            Dim strReceiversFromParm As String = ""
            strReceiversFromParm = ReadParm(strAppPath & "Data\" & strID & "\meta\parm.dat", "RECEIVERS")
            Dim strPasswordFromParm As String = ""
            strPasswordFromParm = ReadParm(strAppPath & "Data\" & strID & "\meta\parm.dat", "PASSWORD")
            If UCase(strReceiversFromParm).Contains(UCase(txtUsername.Text)) AndAlso strPasswordFromParm = txtPassword.Text Then bolPassedSecondAuthenticationTest = True
            If UCase(strSenderFromParm) = UCase(txtUsername.Text) AndAlso strPasswordFromParm = txtPassword.Text Then bolPassedSecondAuthenticationTest = True
            Dim objUsername As New System.Net.Mail.MailAddress(txtUsername.Text)
            If ValidateActiveDirectoryLogin(LookupDomainName, objUsername.User, txtPassword.Text) = True Then bolPassedSecondAuthenticationTest = True
            If bolPassedSecondAuthenticationTest = False Then
                objMultiView.ActiveViewIndex = 1 'SET THE VIEW TO LOGIN PAGE
                litMessageViewUsernamePassword.Text = "<font style=""color:red"">Invalid because username or password are incorrect</font>" : Exit Sub
            End If
            Dim strPageContent As String = ""
            Dim objFiles As System.Collections.ObjectModel.ReadOnlyCollection(Of String)
            objFiles = My.Computer.FileSystem.GetFiles(strDirectoryName, FileIO.SearchOption.SearchTopLevelOnly, "*.*")
            If objFiles.Count <> 0 Then
                strPageContent += "<hr>"
                strPageContent += "<b>Attachment Download</b> (<a target=""_blank"" href=""Viewer.ashx?id=" & strID & "&mode=zip"">All Files as One .ZIP</a>)<br>"
                Dim intCount As Integer
                For Each objFile In objFiles
                    intCount += 1
                    strPageContent += intCount & ") <a target=""_blank"" href=""Viewer.ashx?id=" & strID & "&file=" & System.IO.Path.GetFileName(objFile) & " "">" & UCase(System.IO.Path.GetFileName(objFile)) & "</a><br>"
                Next
                strPageContent += "<hr>"
            End If
            If System.IO.File.Exists(strDirectoryName & "\meta\content.txt") Then
                strPageContent += "<b>Secure Text</b><br>"
                Dim strSecureText As String = ""
                If System.IO.File.Exists(strDirectoryName & "\meta\content.txt") Then strSecureText = System.IO.File.ReadAllText(strDirectoryName & "\meta\content.txt")
                If strSecureText.ToUpper.Contains("<HTML") = False Then strSecureText = Replace(strSecureText, vbCrLf, "<br>") 'HANDLE NON HTML BODIES BY REPLACING CARRIAGE RETURNS
                If strSecureText = "" Then
                    strPageContent += "No secure text sent."
                Else
                    strPageContent += strSecureText
                End If
                strPageContent += "<hr>"
            End If
            litMessageViewAttachmentsAndSecureText.Text = strPageContent
            Session("LOGGEDIN" & strID) = "YES"
        Catch
            Response.Write("Error in Page_Load: " & Err.Description)
        End Try
    End Sub

    Public Function ReadParm(ByVal pstrFileName As String, ByVal pstrParmName As String) As String
        Try
            Dim objReader As System.IO.StreamReader
            If System.IO.File.Exists(pstrFileName) = True Then
                objReader = System.IO.File.OpenText(pstrFileName)
                Dim strCurrentLine = objReader.ReadLine 'READS THE FIRST LINE OF THE PARM FILE
                While Not IsNothing(strCurrentLine) 'LOOPS THROUGH THE FILE UNTIL COMPLETE OR UNTIL THE PARM NAME IS FOUND
                    If InStr(strCurrentLine, "=") > 0 Then
                        Dim strCurrentLineParmName As String = strCurrentLine
                        strCurrentLineParmName = Strings.Left(strCurrentLineParmName, (InStr(strCurrentLineParmName, "=") - 1))
                        If UCase(strCurrentLineParmName) = UCase(pstrParmName) Then 'PARSES LINE TO DISCOVER IF IT CONTAINS DESIRED PARM
                            objReader.Close()
                            Return Strings.Mid(strCurrentLine, (InStr(strCurrentLine, "=") + 1)) 'RETURNS THE PARM VALUE
                            Exit Function
                        End If
                    End If
                    strCurrentLine = objReader.ReadLine 'MOVES TO THE NEXT LINE
                End While
                objReader.Close()
                Return ""
                Exit Function
            Else
                Return ""
                Exit Function
            End If
        Catch
            Return ""
        End Try
    End Function

    Private Function ValidateActiveDirectoryLogin(ByVal strDomain As String, ByVal strUsername As String, ByVal strPassword As String) As Boolean
        Try
            Dim bolSuccess As Boolean = False
            Dim objEntry As New System.DirectoryServices.DirectoryEntry("LDAP://" & strDomain, strUsername, strPassword)
            Dim objSearcher As New System.DirectoryServices.DirectorySearcher(objEntry)
            objSearcher.SearchScope = DirectoryServices.SearchScope.Subtree
            Try
                Dim objResults As System.DirectoryServices.SearchResult = objSearcher.FindOne
                If objResults IsNot Nothing Then bolSuccess = True
            Catch
                bolSuccess = False
            End Try
            Return bolSuccess
        Catch
            Return ""
        End Try
    End Function

    Private Function LookupDomainName() As String
        Try
            Using objSearcher As New System.Management.ManagementObjectSearcher(New System.Management.SelectQuery("Win32_ComputerSystem"))
                For Each objManagementObject As System.Management.ManagementObject In objSearcher.[Get]()
                    Dim strDomainName As String = String.Format("{0}", If(CBool(objManagementObject("partofdomain")), objManagementObject("domain"), objManagementObject("workgroup")))
                    Return strDomainName
                Next
            End Using
            Return ""
        Catch
            Return ""
        End Try
    End Function
End Class
